//
//  LEEStatuseViewModel.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/16.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit

class LEEStatuseViewModel: NSObject {
    
    /// 头像
    var iconUrl : URL?
    
    /// 会员等级
    var mbmarkImage : UIImage?
    
    /// 认证图片
    var avatarImage : UIImage?
    
    /// 行高
    var rowHeight : CGFloat = 300
    
    
    /// 发布时间
    var sendTime: String? {
        //"Sat Nov 19 20:30:03 +0800 2016"
//        let str = "Sat Nov 18 20:30:03 +0800 2016"
        
//        let timeStr = statuse?.created_at
        
        let dateFormatter = dateFormater
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //在真机上必须设置本地化信息否则转换失败
        dateFormatter.locale = Locale(identifier: "en")
        
        guard let sinceDate = dateFormatter.date(from: statuse!.created_at ?? "") else {
            return "来自火星"
        }
        //2016-11-19 12:30:03 +0000
//        print(sinceDate)
        let calendar = Calendar.current
        //当前时间
        let currentDate = Date()
        
        let result = calendar.dateComponents([.day,.year], from: sinceDate, to: currentDate)
        
        if result.year == 0 {
           //当年
            if calendar.isDateInToday(sinceDate) {
                //今天
                //获取当前时间和sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinceDate)
                
                if delta < 60 {
                    //刚刚
                    return "刚刚"
                }else if delta < 3600 {
                    //##分钟前
                    return "\(Int(delta/60))分钟前"
                }else{
                    //##小时前
                    return "\(Int(delta/3600))小时前"
                }
                
            }else if calendar.isDateInYesterday(sinceDate){
                //昨天 HH:mm
                dateFormatter.dateFormat = "昨天 HH:mm"
                return dateFormatter.string(from: sinceDate)
            
            }else{
                ///其他 MM-dd HH:mm
                dateFormatter.dateFormat = "MM-dd HH:mm"
                return dateFormatter.string(from: sinceDate)
            }
            
        }else{
        
            dateFormatter.dateFormat = "yyyy-MM-dd"
            return dateFormatter.string(from: sinceDate)
        }
        
    }
    
    /// 微博来源
    var weiboSource: String?
    
    /// 原创微博内容
    var originalText: NSMutableAttributedString?
    
    /// 转发微博内容
    var retweetedText: NSMutableAttributedString?
    
    
    
    var imgUrls: [LEEPic_url]? {
        
        if statuse?.retweeted_status == nil {
            
            return statuse?.pic_urls
        }
        
        return statuse?.retweeted_status?.pic_urls
    }
    
    var statuse : LEEWeiboStatuses? {
    
        didSet {
        
            iconUrl = URL(string: statuse?.user?.avatar_large ?? "")
            chooseMbmarkImage(mbmark: statuse?.user?.mbrank ?? 0)
            chooseAvatarImage(avatar: statuse?.user?.verified_type ?? -1)
            weiboSource = weiboSource(source: statuse?.source ?? "")
            
            self.originalText = dealWeiboText(str: statuse?.text ?? "")
            self.retweetedText = dealWeiboText(str: statuse?.retweeted_status?.text ?? "")
        }
    }
    
    //MARK: 将微博正文/转发微博正文处理成富文本
    private func dealWeiboText(str: String) -> NSMutableAttributedString {
    
        //1.实例化正则表达式对象
//        let pattern = "\\[.*?\\]"
//        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        let results = emoticonRegex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        //3.遍历结果集  获取表情字符串  ->> 倒序遍历
        //4. 将str转换可变的富文本
        let strM = NSMutableAttributedString(string: str)
        let font = UIFont.systemFont(ofSize: 18)
        let fontHeight = font.lineHeight
        
        for result in results.reversed() {
            
            let range = result.rangeAt(0)
            
            let sub = (str as NSString).substring(with: range)
            
            print(sub)
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticonByImageName(str: sub) {
                //查找到表情模型就开始后续的操作
                /*
                 // 嵌入 UIImage
                 UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
                 attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
                 [text appendAttributedString: attachment];
                 */
                let img = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)

                let attachment = NSMutableAttributedString.yy_attachmentString(withContent: img, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: fontHeight, height: fontHeight), alignTo: font, alignment: .center)
                
                //将图片富文本替换到str对应的可变的富文本中
                strM.replaceCharacters(in: range, with: attachment)
            }
        }
        strM.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 18)], range: NSRange(location: 0, length: strM.length))
        
        addHighlighted(regex: atSomeRegex, strM: strM)
        addHighlighted(regex: topicRegex, strM: strM)
        addHighlighted(regex: urlRegex, strM: strM)
        
        
        return strM
    }
    //MARK: 将微博正文/转发微博正文关键字高亮
    func addHighlighted(regex: NSRegularExpression ,strM: NSMutableAttributedString) {
        
        
        
        let str = strM.string
        
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        for result in results {
            
            let range = result.rangeAt(0)
            //给目标字符串添加颜色
            strM.addAttributes([NSForegroundColorAttributeName : UIColor.orange], range: range)
            
            ////给特殊的文本添加点击事件  使用YYText
            /*
             // 1. 创建一个"高亮"属性，当用户点击了高亮区域的文本时，"高亮"属性会替换掉原本的属性
             YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
             
             YYTextHighlight *highlight = [YYTextHighlight new];
             [highlight setColor:[UIColor whiteColor]];
             [highlight setBackgroundBorder:highlightBorder];
             highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
             NSLog(@"tap text range:...");
             // 你也可以把事件回调放到 YYLabel 和 YYTextView 来处理。
             };
             // 2. 把"高亮"属性设置到某个文本范围
             [attributedText yy_setTextHighlight:highlight range:highlightRange];
             */
            let border = YYTextBorder(fill: UIColor.gray, cornerRadius: 3)
            
            let highlight = YYTextHighlight()
            highlight.setColor(UIColor.white)
            highlight.setBackgroundBorder(border)
            
            strM.yy_setTextHighlight(highlight, range: range)
        }
        
    }
    
     /// 微博来源
    private func weiboSource(source: String) -> String {
        //"<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>"
        
        let startFlag = "\">"
        let endFlag = "</a>"
        guard let startRange = source.range(of: startFlag),
            let endRange = source.range(of: endFlag)
            else {
            return "来自星星"
        }
        //upperBound 最大边界 lowerBound: 最小边界
        let range = startRange.upperBound..<endRange.lowerBound
        
        return source.substring(with: range)
    }
    
    
    /// 选择vip 等级图片
    private func chooseMbmarkImage(mbmark : Int) {
        
        if mbmark < 7 && mbmark > 0 {
            
            mbmarkImage = UIImage(named: "common_icon_membership_level\(mbmark)")
    
        }else{
        
            mbmarkImage = UIImage(named: "common_icon_membership_expired")
        }
    }
    
    /// 选择认证 等级图片 认证类型: -1：没有认证，0：认证用户，2,3,5: 企业认证，220: 达人
    private func chooseAvatarImage(avatar : Int) {
    
        switch avatar {
        case 0:
            avatarImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            avatarImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            avatarImage = UIImage(named: "avatar_grassroot")
            
        default:
            avatarImage = UIImage(named: "")
        }
    
    }
    
    
    
}
